<template>
  <el-dialog :title="title"
             v-if="open"
             :visible.sync="open"
             :modal=true
             width="80%"
             center
  >
    <div class="app-container">
      <el-form ref="form" :model="form" :rules="rules" label-width="150px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="入库单编号" prop="recptCode">
              <el-input v-model="form.recptCode" placeholder="请输入入库单编号" :readonly="optType!='add'"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="入库单名称" prop="recptName">
              <el-input v-model="form.recptName" placeholder="请输入入库单名称"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="入库日期" prop="recptDate">
              <el-date-picker clearable
                              v-model="form.recptDate"
                              type="date"
                              value-format="yyyy-MM-dd"
                              placeholder="请选择入库日期" style="width: 100%"
                              :default-value="new Date()">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="供应商" prop="vendorName">
              <el-input v-model="form.vendorName" readonly="readonly" placeholder="请选择供应商">
                <el-button slot="append" @click="handleSelectVendor" icon="el-icon-search"
                           :disabled="form.isConcession==='Y'"></el-button>
              </el-input>
              <VendorSelect ref="vendorSelect" @onSelected="onVendorSelected"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="到货单编号" prop="arrivedCode">
              <el-input v-model="form.arrivedCode" readonly placeholder="请选择到货单">
                <el-button slot="append"
                           @click="handleSelectArrived" icon="el-icon-search"
                           v-if="optType != 'execute' && optType != 'view'"></el-button>
              </el-input>
              <ArrivedSelect ref="arrivedSelect" @onSelected="onArrivedSelected" :vendorId="form.vendorId" v-if="form.vendorId"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入备注" maxlength="250"/>
        </el-form-item>

        <!--横线组件纯纯为了页面好看-->
        <el-divider></el-divider>
        <el-row style="margin-bottom: 20px;">
          <el-col :span="1.5">
            <div style="font-size: 20px; margin-top: 5px">入库物料</div>
          </el-col>
          <el-col :span="5">
            <el-button type="primary" @click="handleAdd" style="margin-left: 20px;"
                       v-if="form.arrivedCode && form.isConcession !=='Y'">
              点击添加入库物料
            </el-button>
          </el-col>
        </el-row>
        <el-table border :data="addGoodsList">
          <el-table-column label="物料名称" align="center" prop="itemName" width="150" fixed="left"/>
          <el-table-column label="物料编号" align="center" prop="itemCode" width="150"/>
          <el-table-column label="到货单编号" align="center" prop="arrivedCode" width="150"/>
          <el-table-column label="订单编号" align="center" prop="orderCode" width="150"/>
          <el-table-column label="规格型号" align="center" prop="specification" width="150"/>
          <el-table-column label="单位" align="center" prop="unitOfMeasure" width="150"/>
          <el-table-column label="分类" align="center" prop="itemTypeName" width="150"/>
          <el-table-column
            v-for="col in columnsConfig"
            :key="col.prop"
            :label="col.label"
            :prop="col.prop"
            :width="col.width"
            :align="col.align"
            v-if="col.show">
          </el-table-column>
          <el-table-column label="客户" align="center" prop="clientName" width="150"/>
          <el-table-column label="最大入库数量(主)" align="center" prop="maxQuantityRecived" width="200">
            <template slot-scope="scope">
              <span>{{ scope.row.maxQuantityRecived }} / {{ scope.row.unitOfMeasure }}</span>
            </template>
          </el-table-column>
          <el-table-column label="入库数量(主)" align="center" prop="quantityRecived" width="200">
            <div class="item" slot-scope="scope">
              <el-input-number v-model="scope.row.quantityRecived" controls-position="right" :precision="2" :min="1"
                               :max="scope.row.maxQuantityRecived" size="mini" style="width:130px"
                               :disabled="form.isConcession==='Y' || scope.row.storageUnitType==='fixed'"/>
              <span>{{ ' / ' + scope.row.unitOfMeasure }}</span>
            </div>
          </el-table-column>
          <el-table-column label="入库数量(辅)" align="center" prop="storageUnitquantity" width="200">
            <div class="item" slot-scope="scope">
              <el-input-number v-model="scope.row.storageUnitquantity" controls-position="right" :precision="2" :min="1"
                               size="mini" style="width:130px"
                               :max="scope.row.storageUnitType === 'fixed' && scope.row.storageRatio > 0 ?
              (scope.row.maxQuantityRecived / scope.row.storageRatio) : Infinity"
                               :disabled="form.isConcession==='Y' "
                               v-if="scope.row.enableMultiUnit==='Y'"
                               @change="handleStorageUnitQuantityChange(scope.row)"/>
              <span v-if="scope.row.enableMultiUnit === 'Y'">{{ ' / ' + scope.row.storageUnit }}</span>
            </div>
          </el-table-column>

          <el-table-column label="入库位置" align="center" prop="warehouseInfo" width="150">
            <template slot-scope="scope">
              <el-cascader v-model="scope.row.warehouseInfo"
                           :options="warehouseOptions"
                           :props="warehouseProps"
                           @change="handleWarehouseChanged(scope.row)"
              >
              </el-cascader>
            </template>
          </el-table-column>
          <el-table-column label="入库批次" align="center" prop="batchCode" width="150">
            <template slot-scope="scope">
             <el-input v-model="scope.row.batchCode" placeholder="请输入批次号" style="width: 100%" :readonly="scope.row.enableBatchFlag === 'N'"/>
            </template>
          </el-table-column>
          <el-table-column label="生产日期" align="center" prop="manufactureDate" width="180">
            <template slot-scope="scope">
              <el-date-picker clearable
                              v-model="scope.row.manufactureDate"
                              type="date"
                              value-format="yyyy-MM-dd"
                              @change="(val) => handleManufactureDateChange(val, scope.row)"
                              :disabled="scope.row.enablePeriod === 'N'"
                              placeholder="生产日期" style="width: 100%">
              </el-date-picker>
            </template>
          </el-table-column>
               <el-table-column label="到期日期" align="center" prop="expireDate" width="180">
                      <template slot-scope="scope">
                        <el-date-picker clearable
                                        v-model="scope.row.expireDate"
                                        type="date"
                                        value-format="yyyy-MM-dd"
                                        placeholder="请选择到期日期" style="width: 100%">
                        </el-date-picker>
                      </template>
                </el-table-column>
          <el-table-column label="操作" align="center" class-name="small-padding fixed-width" fixed="right">
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="text"
                icon="el-icon-edit"
                @click="deleteGoodsList(scope.row)"
                v-if="form.isConcession !=='Y'"
              >删除商品
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-form>
      <div slot="footer" class="dialog-footer" style="text-align:center;margin-top: 20px;">
        <el-button type="primary" @click="submitForm">保存入库单</el-button>
        <el-button type="primary" @click="cancel">返 回</el-button>
      </div>

      <!--选择商品信息弹出框-->
      <ItemSelect ref="itemSelect" @onSelected="onItemSelected" :arrivedCode="form.arrivedCode"
                  v-if="form.arrivedCode" :quantityRecived="quantityRecived"></ItemSelect>
    </div>
  </el-dialog>
</template>

<script>
import {getItemrecpt, updateItemrecpt} from "@/api/mes/wm/itemrecpt";
import {addItemrecpt,} from "@/api/mes/wm/itemrecpt";
import {genCode} from "@/api/system/autocode/rule"
import ItemSelect from "@/views/mes/wm/itemrecpt/itemSelect.vue";
import VendorSelect from "@/components/vendorSelect/single.vue";
import {getTreeList} from "@/api/mes/wm/warehouse";
import {getColumnsConfigKey} from "@/api/system/columnsconfig";
import ArrivedSelect from "@/views/mes/wm/itemrecpt/arrievdSelect.vue";

export default {
  name: "AddOrUpdate",
  components: {ArrivedSelect, ItemSelect, VendorSelect},
  dicts: ['erp_payment_type'],
  data() {
    return {
      title: null,
      quantityRecived: {},
      optType: '',
      warehouseOptions: [],
      warehouseProps: {
        multiple: false,
        value: 'pId',
        label: 'pName',
      },
      open: false,
      // 遮罩层
      loading: true,
      // 添加的商品信息表格数据
      addGoodsList: [],
      // 供应商列表
      vendorList: [],
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        recptCode: [
          {required: true, message: "入库单编号不能为空", trigger: "blur"}
        ],
        recptDate: [
          {required: true, message: "入库日期不能为空", trigger: "change"}
        ],
        // recptName: [
        //   {required: true, message: "入库名称不能为空", trigger: "blur"}
        // ],
        vendorName: [
          {required: true, message: "供应商不能为空", trigger: "blur"}
        ]

      },
      columnsConfig: [],
    };
  },
  created() {
    /* this.getList();
     //查询商品表方法
     this.getGoodsList();
     //查询供应商列表方法
     this.getSupplierlist();*/
    this.getItemBase();
  },
  watch: {
    'form.vendorId'(newVal, oldVal) {
      if (!oldVal) return;
      if (newVal !== oldVal) {
        this.addGoodsList = [];
      }
    },
    'form.arrivedCode'(newVal, oldVal) {
      if (!oldVal) return;
      if (newVal !== oldVal) {
        this.addGoodsList = [];
      }
    }
  },
  methods: {
    init(id) {
      this.quantityRecived = {};
      this.resetForm("form");
      if (id) {
        this.title = "修改入库单";
        getItemrecpt(id).then(response => {
          this.form = response.data;
          if (response.data) {
            response.data.wmItemRecptLineList.forEach(item => {
              this.quantityRecived[item.arrivedLineId] = item.quantityRecived;
            })
          }
          this.addGoodsList = response.data.wmItemRecptLineList;
          this.addGoodsList.forEach(item => {
            item.warehouseInfo = [];
            item.warehouseInfo[0] = item.warehouseId;
            item.warehouseInfo[1] = item.locationId;
            item.warehouseInfo[2] = item.areaId;

          })
        })
      } else {
        this.title = "新增入库单";
        this.form = {
          recptCode: null,
          recptName: null,
          recptDate: new Date().toISOString().split('T')[0],
          remark: null,
          vendorId: null,
          vendorName: null,
          vendorCode: null,
          isConcession: 'N',
          arrivedCode:null
        };
        this.handleAutoGenChange();
        this.addGoodsList = [];
      }
      this.getWarehouseList();
    },
    //删除添加的商品方法
    deleteGoodsList(row) {
      this.addGoodsList.splice(this.addGoodsList.indexOf(row), 1);
    },
    // 取消按钮
    cancel() {
      this.open = false;
    },
    // 处理生产日期变化
    handleManufactureDateChange(date, row) {
      if (date && row.enablePeriod == 'Y') {
        console.log(row.qualityGuaranteePeriod)
        this.calculateExpiryDate(row);
      }
    },
    // 计算到期日期
    calculateExpiryDate(row) {
      if (!row.manufactureDate){
        this.$modal.msgError("请填写生产日期");
        return;
      }

      const manufactureDate = new Date(row.manufactureDate);
      console.log("33333",manufactureDate)
      // 获取生产日期的年月日
      const year = manufactureDate.getFullYear();
      const month = manufactureDate.getMonth();
      const day = manufactureDate.getDate();

      // 计算到期日期的月份和年份
      let expiryMonth = month + parseInt(row.qualityGuaranteePeriod);
      let expiryYear = year;

      // 处理月份超过12的情况
      while (expiryMonth >= 12) {
        expiryMonth -= 12;
        expiryYear += 1;
      }

      // 创建新的日期对象
      const expiryDate = new Date(expiryYear, expiryMonth, day);

      // 处理2月特殊情况（如生产日期是1月31日，2月没有31日）
      if (expiryDate.getDate() !== day) {
        // 如果日期不匹配，说明是月末情况，设置为最后一天
        expiryDate.setDate(0); // 设置为上个月的最后一天
      }

      // 格式化为yyyy-MM-dd
      const formattedDate = `${expiryYear}-${(expiryMonth + 1).toString().padStart(2, '0')}-${expiryDate.getDate().toString().padStart(2, '0')}`;
      console.log("3333333333333",formattedDate)
      // 更新到期日期expireDate   expireDate
      this.$set(row, 'expireDate', formattedDate);
      this.$forceUpdate()
    },
    /** 新增采购商品按钮操作 */
    handleAdd() {
      this.$refs.itemSelect.showFlag = true;
      this.$refs.itemSelect.getList();
      this.$refs.itemSelect.selectedRows2 = this.addGoodsList;
    },
    /** 新增提交按钮 */
    submitForm() {
      let that = this;
      this.$modal.confirm('是否确认保存入库单？').then(function () {
        that.$refs["form"].validate(valid => {
          if (valid) {
            //判断是否添加商品
            if (that.addGoodsList.length === 0) {
              that.$modal.msgError("请添加商品");
              return;
            }
            if (that.addGoodsList.length !== 0) {
              for (let i = 0; i < that.addGoodsList.length; i++) {
                /*if (that.addGoodsList[i].estimatedUnitPrice === null || that.addGoodsList[i].estimatedUnitPrice === "") {
                  that.$modal.msgError("请填写采购单价");
                  return;
                }*/
                if (that.addGoodsList[i].quantityRecived === null || that.addGoodsList[i].quantityRecived === undefined) {
                  that.$modal.msgError("请填写入库数量");
                  return;
                }
                if (that.addGoodsList[i].quantityRecived <= 0) {
                  that.$modal.msgError("请填写正确的入库数量");
                  return;
                }
                /* console.log('33333333',that.addGoodsList[i].warehouseInfo)
                 console.log('4444444444',that.addGoodsList[i].warehouseId)*/
                if (that.addGoodsList[i].warehouseInfo == null || that.addGoodsList[i].locationId == null || that.addGoodsList[i].areaId == null) {
                  that.$modal.msgError("请填写入库位置");
                  return;
                }

                if (that.addGoodsList[i].enablePeriod == 'Y' && that.addGoodsList[i].manufactureDate === null) {
                  that.$modal.msgError("请填写生产日期");
                  return;
                }
                //判断是否开启批次管理开启必须输入批次号
                if(that.addGoodsList[i].enableBatchFlag == 'Y' && that.addGoodsList[i].batchCode===null){
                  that.$modal.msgError("请填写批次号");
                  return;
                }
              }
            }

            that.form.wmItemRecptLineList = that.addGoodsList;
            if (that.form.recptId) {
              updateItemrecpt(that.form).then(response => {
                that.$modal.msgSuccess("修改成功");
                that.open = false;
                that.$parent.getList();
                that.cancel();
              })
            } else {
              //调取新增接口
              addItemrecpt(that.form).then(response => {
                that.$modal.msgSuccess("新增成功");
                that.open = false;
                that.$parent.getList();
                that.cancel();
              });
            }
          }
        })


      });
    },
    //自动生成编码
    handleAutoGenChange() {
        genCode('ITEMRECPT_CODE').then(response => {
          this.form.recptCode = response;
        });
    },
    //物料选择弹出框
    onItemSelected(obj) {
      if (this.addGoodsList && this.addGoodsList.length > 0) {
        this.addGoodsList.forEach((item, index) => {
          obj.find((item1) => {
            if (item.arrivedLineId == item1.arrivedLineId) {
              item1.quantityRecived = item.quantityRecived;
              item1.warehouseInfo = item.warehouseInfo;
              item1.warehouseId = item.warehouseId;
              item1.locationId = item.locationId;
              item1.areaId = item.areaId;
              item1.manufactureDate = item.manufactureDate;
              if (item.lineId) {
                item1.lineId = item.lineId;
              }

            }
          })
        })
      }
      obj.forEach(item => {
        if (item.enableMultiUnit === 'Y' && item.storageUnitType === 'fixed')
          item.storageUnitquantity = parseFloat((item.quantityRecived / item.storageRatio).toFixed(2));
      })
      this.addGoodsList = obj;
    },
    //供应商选择
    handleSelectVendor() {
      this.$refs.vendorSelect.showFlag = true;
    },
    //供应商选择弹出框
    onVendorSelected(obj) {
      if (obj != undefined && obj != null) {
        this.form.vendorId = obj.vendorId;
        this.form.vendorCode = obj.vendorCode;
        this.form.vendorName = obj.vendorName;
        if (obj.contact1 != null && obj.contact1Tel != null) {
          this.form.contact = obj.contact1;
          this.form.contactTel = obj.contact1Tel;
        } else {
          this.form.contact = obj.contact2;
          this.form.contactTel = obj.contact2Tel;
        }
      }
    },
    getWarehouseList() {
      getTreeList().then(response => {
        if (response.data) {
          this.warehouseOptions = response.data.filter((el) => {
            return el.warehouseCode.indexOf('VIR') == -1;
          });
          ;
        }
        this.warehouseOptions.map(w => {
          w.children.map(l => {
            let lstr = JSON.stringify(l.children).replace(/locationId/g, 'lId').replace(/areaId/g, 'pId').replace(/areaName/g, 'pName');
            l.children = JSON.parse(lstr);
          });

          let wstr = JSON.stringify(w.children).replace(/warehouseId/g, 'wId').replace(/locationId/g, 'pId').replace(/locationName/g, 'pName');
          w.children = JSON.parse(wstr);

        });
        let ostr = JSON.stringify(this.warehouseOptions).replace(/warehouseId/g, 'pId').replace(/warehouseName/g, 'pName');
        this.warehouseOptions = JSON.parse(ostr);

      });
    },
    //选择仓库、库区、库位
    handleWarehouseChanged(row) {
      let obj = row.warehouseInfo;
      if (obj != null) {
        row.warehouseId = obj[0];
        row.locationId = obj[1];
        row.areaId = obj[2];
      }
    },
    getItemBase() {
      getColumnsConfigKey('MdItem_Base').then(res => {
        this.columnsConfig = JSON.parse(res.data);
      })
    },
    handleStorageUnitQuantityChange(row) {
      if (row.storageUnitType === 'fixed') {
        // 计算主单位数量 = 辅单位数量 * 比例
        let quantityRecived = row.storageUnitquantity * row.storageRatio;

        // 检查主单位数量是否超过上限
        if (quantityRecived > row.maxQuantityRecived) {
          // 如果超过上限，将主单位设为最大值
          row.quantityRecived = row.maxQuantityRecived;
          // 反向计算辅单位数量 = 上限值 / 比例
          row.storageUnitquantity = parseFloat((row.maxQuantityRecived / row.storageRatio).toFixed(2));
        } else {
          // 保留2位小数（与主单位输入框精度一致）
          row.quantityRecived = parseFloat(quantityRecived.toFixed(2));
        }
      }
    },
    //采购到货单选择
    handleSelectArrived() {
      this.$refs.arrivedSelect.showFlag = true;
      this.$refs.arrivedSelect.getList();
    },
    //采购到货单选择弹出框
    onArrivedSelected(obj) {
      debugger
      this.form.arrivedCode = obj.arrivedCode;
    },
  }
};
</script>

<style scoped>

</style>
